<template>
    <div class="loan-in-want-index">
        <div class="wrapper" v-show='pageLoaded'>
            <ul class="form-box">
                <li class="form__item">
                    <span class="form__key">借款金额</span>
                    <div class="form__value">
                        <input @keyup='setMax' @change='calc' v-model='amount' type="tel" :placeholder="amoutPlaceholder">
                    </div>
                </li>
                <li class="form__item detail select" v-if='!isPublish'>
                    <span class="form__key">借款时长</span>
                    <div class="form__value" v-if='detail.daysType == "DAY"'>
                        <picker-list key='days' picker-id='days' :list='daysList' v-model='days' @done='calc'></picker-list>
                    </div>
                    <div class="form__value" v-if='detail.daysType == "PERIOD"'>
                        <picker-list key='periods' picker-id='periods' :list='periodsList' v-model='periods' @done='calc'></picker-list>
                    </div>
                </li>
            </ul>
            <!-- 我的借条 -->

            <ul class="form-box">
                <li class="form__item select" :class="{ 'disabled':!isPublish }" v-if='!isPublish'>
                    <span class="form__key">还款方式</span>
                    <div class="form__value">
                        <p class='item'> {{ detail.repayWayStr }} </p>
                    </div>
                </li>
                <li class="form__item detail select repay-time" v-if='isPublish'>
                    <template v-if='payway == "HBFX"'>
                        <span class="form__key">借款时长</span>
                        <div class="form__value">
                            <picker-list key='month' picker-id='month' :list='month' v-model='monthSelect' @done='calc'></picker-list>
                        </div>
                    </template>
                    <template v-else>
                        <span class="form__key">借款时长</span>
                        <div class="form__value">
                            <picker-list key='periods' picker-id='periods' :list='periodsList' v-model='periods' @done='calc'></picker-list>
                        </div>
                    </template>
                </li>
                <!-- <li class="form__item select" :class="{ 'disabled':!isPublish }">
                    <span class="form__key">年化利率</span>
                    <div class="form__value have-two-item" v-if='isPublish'>
                        <picker-list picker-id='yearRate' :list='yearRateList' v-model='yearRate' @done='calc'>
                            <p>{{calcObject.interestAmount | toYuan}}</p>
                        </picker-list>
                    </div>
                    <div class="form__value" v-else>
                        <p class='item'> {{ detail.yearRate/100 + "%" }} </p>
                    </div>
                </li> -->
                <!-- <li class="form__item" :class="{ 'disabled':!isPublish }" v-if='isPublish'>
                    <span class="form__key" @click='showServiceTips = true'>服务费<i class="info"></i> </span>
                    <div class="form__value">
                        <input @change='serviceFeeChange' v-model='serviceFee' type="tel" placeholder="请输入整数(元)">
                    </div>
                </li> -->
                <li class="form__item" :class="{ 'disabled':!isPublish }" v-if='!isPublish'>
                    <span class="form__key">服务费率</span>
                    <div class="form__value">
                        <p class='item year-rate'>{{ caclServiceFeeRate(detail.serviceFeeRate) }} <small>(不足{{ detail.serviceFee/100 + "元" }}按{{ detail.serviceFee/100 + "元" }}收取)</small></p>
                    </div>
                </li>

                <li class="form__item select" v-if='usageList.length'>
                    <span class="form__key">借款用途</span>
                    <div class="form__value">
                        <picker-list key="usage" picker-id='usage' :list='usageList' v-model='usage'></picker-list>
                    </div>
                </li>
                <li class="form__item select" v-if='addressList.length > 0'>
                    <span class="form__key">所在地区</span>
                    <div class="form__value">
                      <citys
                          :cityList = 'addressList'
                          :select-city='cityInfo.cityName'
                          @set='setCity' >
                      </citys>
                        <!-- <picker-list key="address" picker-id='address' :list='addressList' v-model='address'></picker-list> -->
                    </div>
                </li>
            </ul>

            <!-- <ul class="form-box"> -->
                <!-- <li class="form__item has-arrow detail" @click='goUse'>
                    <span class="form__key">借款用途及说明</span>
                    <div class="form__value" v-if='loanInForm.usage'>
                        <p class='item'> {{loanInForm.usage}} </p>
                    </div>
                    <i class="iconfont icon-arrow"></i>
                </li> -->
                <!-- <li class="form__item detail select" v-if='!isPublish'>
                    <span class="form__key">授权出借人查看电话姓名</span>
                    <div class="form__value">
                        <picker-list picker-id='isAccredit' :list='isAccredits' v-model='isAccredit'></picker-list>
                    </div>
                </li> -->
                <!-- <li class="form__item detail select" v-if='isPublish'>
                    <span class="form__key">所有人可见</span>
                    <div class="form__value">
                        <picker-list picker-id='isPublic' :list='isPublics' v-model='isPublic'></picker-list>
                    </div>
                </li> -->
            <!-- </ul> -->

            <transition name="fade">
                <div class="card money-info" v-show='!noCalc'>
                    <div class="money-info__header">
                        <div class="money-info__box">
                            <h1 class="money-info__title">实际到账金额</h1>
                            <div class='calc-content'>
                                <p class="money-info__item">
                                    <span class="money-info__key">借款金额</span>
                                    <span class="money-info__value">{{ calcObject.borrowAmount | toYuan }}</span>
                                </p>
                                <p class="money-info__item">
                                    <span class="money-info__key">服务费</span>
                                    <span class="money-info__value">-{{ calcObject.serviceFee | toYuan }}</span>
                                </p>
                                <p class="money-info__item">
                                    <span class="money-info__key">手续费</span>
                                    <span class="money-info__value">-{{ calcObject.commissionFee | toYuan }}</span>
                                </p>
                                <p class="money-info__number">{{ calcObject.receiveAmount | toYuan }}元</p>
                            </div>
                        </div>
                        <div class="money-info__box">
                            <h1 class="money-info__title">预计还款本息</h1>
                            <div class='calc-content'>
                                <p class="money-info__item">
                                    <span class="money-info__key">本金</span>
                                    <span class="money-info__value">{{ calcObject.borrowAmount | toYuan }}</span>
                                </p>
                                <p class="money-info__item">
                                    <span class="money-info__key">利息</span>
                                    <span class="money-info__value">+{{ calcObject.interestAmount | toYuan }}</span>
                                </p>
                                <p class="money-info__item today">
                                    <span class="money-info__key"></span>
                                    <span class="money-info__value">-</span>
                                </p>
                                <p class="money-info__number">{{ calcObject.repayAmount | toYuan }}元</p>
                            </div>
                        </div>
                    </div>
                    <div class="plan">
                        <div class="money-info__box">
                            <h1 class="money-info__title">还款计划<small>（假设今天借到钱）</small></h1>
                            <p class="money-info__item" v-for='item in calcObject.repayPlanList'>
                                <span class="money-info__key">{{item.shouldRepayDate | dateFormat}} 还款</span>
                                <span class="money-info__value">{{item.repayAmount | toYuan}}</span>
                            </p>
                        </div>
                    </div>
                    <loading v-show='loading_calc' mode='fullscreen' :size='18'></loading>
                </div>
            </transition>

            <div class="form__agreement">
                <check-box v-model='agreementCheck'><span class='form__agreement-text'>已阅读并同意 <em @click.stop='showAgreement = true'>《有借借款协议》</em> </span></check-box>
            </div>
            <!-- <div class="tips">
                <p>提示</p>
                <p>1. 发布的借款信息有效时间为3天，超时自动关闭。</p>
                <p>2. 当前的信息未关闭，不得发起新的求借款。</p>
                <p>3. 平台手续费=借款金额*1%，用于借款期间生成的各项费用，由借款人承担，在款项到账后平台直接扣除。</p>
            </div> -->

            <div class="tips">
              <p>提示</p>
              <p>1. 在平台储备金范围内，支持所有人任何时间立即提现。</p>
              <p>2. 如果有借筹满／筹款超过3天／还款时间到期，借款将自动关闭。</p>
              <p>3. 当前借款未关闭，不得发布新的借款。</p>
            </div>
        </div>
        <div class="single-button" v-show='pageLoaded'>
            <span class="button" @click='confirm' :class='{disabled : !agreementCheck}'>{{ buttonText }}</span>
        </div>

        <auth-step
            v-if='noAuth'
            :show='showTips'
            @toggle='showTips = !showTips'
            @close='showTips = false'>
        </auth-step>

        <modal
            :show='showServiceTips'
            @close='showServiceTips = false'>
            <div class="modal-tips">
                <p>服务费是什么？ </p>
                <p>服务费最高不超过借款金额12%，由借款人自行设置，平台在交易成功后自动扣取。</p>
            </div>
        </modal>

        <confirm
            :show='show_confirm_borrow'
            @close='show_confirm_borrow = false'
            @confirm='confirmBorrow'
            title='提示'
            tips='警惕要求先付订金，利息，审核费等诈骗行为，如发现立即举报0571-87098933'></confirm>

        <pay-password
            :show='showPayPassword'
            @close='showPayPassword=false'
            @finish='payFinish'></pay-password>

        <agreement
            :show='showAgreement'
            @close='showAgreement=false'></agreement>
    </div>
</template>

<script>
    import { Promise } from 'es6-promise'
    import citys from '../components/Citys.vue'
    import footerBar from '../components/FooterBar.vue'
    import selectGroup from '../components/SelectGroup.vue'
    import selectOption from '../components/SelectOption.vue'
    import radioGroup from '../components/RadioGroup.vue'
    import areaSelect from '../components/AreaSelect.vue'
    import radio from '../components/Radio.vue'
    import loading from '../components/Loading.vue'
    import checkBox from '../components/CheckBox.vue'
    import toolTip from '../components/ToolTip.vue'
    import modal from '../components/Modal.vue'
    import confirm from '../components/Confirm.vue'
    import buttonLoading from '../components/ButtonLoading.vue'
    import authStep from '../components/AuthStep.vue'
    import pagination from '../components/Pagination.vue'
    import payPassword from '../components/PayPassword.vue'
    import agreement from '../components/Agreement.vue'
    import verificationCode from '../components/VerificationCode.vue'
    import pickerList from '../components/PickerList.vue'
    import pickerDate from '../components/PickerDate.vue'
    import toYuan from '../filters/filter-toYuan'
    import dateFormat from '../filters/filter-dateFormat'
    import yearRateList from '../data/yearRateList'
    import paywayList from '../data/paywayList'
    import daysList from '../data/daysList'
    import month from '../data/days'
    import periodsList from '../data/periodsList'
    import { rules } from '../utils/utils'
    import  { mapGetters, mapActions }  from 'vuex'
    import { LoanInApplyValidation, LoanInPublishValidation } from '../validation/validation'
    import { loanInApi, loanOutApi, userApi } from '../api/api'
    import moment from 'moment'

    export default {
        components:{
            citys,
            footerBar,
            authStep,
            selectGroup,
            selectOption,
            radioGroup,
            radio,
            checkBox,
            areaSelect,
            loading,
            toolTip,
            modal,
            confirm,
            agreement,
            buttonLoading,
            pagination,
            payPassword,
            verificationCode,
            pickerList,
            pickerDate
        },
        filters:{
            toYuan,
            dateFormat
        },
        data() {
            return {
                cityInfo : '',
                number:this.$route.params.number,
                placeholder:'--',
                pageLoaded:false,
                showTips:false,
                showServiceTips:false,
                amount:'',
                days:'',
                monthSelect:'',
                month:month,
                minDate:moment().add(2, 'days'),
                daysList:daysList,
                periods:'',
                periodsList:periodsList,
                quota:'',
                detail:{},
                calcObject:{},
                showPayPassword:false,
                showAgreement:false,
                show_confirm_borrow:false,
                buttonText:'',
                main:{},
                password:'',
                usageList:[],
                address: '',
                addressList: [],
                ip: '',
                // ipProvince: '',
                // ipCity: '',
                usage:'',
                payway:'HBFX',
                paywayList:paywayList,
                isPublics:[{
                    value:1,
                    display:'是'
                },{
                    value:0,
                    display:'否'
                }],
                isPublic:1,
                isAccredits:[{
                    value:1,
                    display:'是'
                },{
                    value:0,
                    display:'否'
                }],
                isAccredit:0,
                yearRate:2400,
                yearRateList:yearRateList,
                serviceFee:0,
                agreementCheck:true,
                payPasswordShow:false,
                payStatus:'',
                userCount:'',
                listInfo:{},
                records:[],
                loading:true,
                loading_calc:false,
            }
        },
        computed:{
            ...mapGetters([
                'msgTip',
                'localInfo',
                'loanInForm'
            ]),
            isPublish(){
                return this.number == 'default'
            },
            userInfo(){
                return this.localInfo.userInfo
            },
            isPay(){
                return this.userInfo.isPay
            },
            noAuth(){
                if(!this.userInfo.creditReport) return true
                return this.userInfo.creditReport.status != 'OK'
            },
            amountToFen(){
                if(this.amount){
                    return (this.amount*100)
                }
            },
            amountRate(){
                if(this.amount && this.yearRate){
                    return (this.amount*this.yearRate/10000).toFixed(2) + '元'
                }
            },
            amountFrom(){
                if(this.detail){
                    return toYuan(this.detail.lendAmountFrom)
                }
            },
            amountTo(){
                if(this.detail){
                    return toYuan(this.detail.lendAmountTo)
                }
            },
            amoutPlaceholder(){
                if(this.isPublish) return '请输入整数（100 - 9000元）'

                return `请输入${Number(this.amountFrom)} ~ ${Number(this.amountTo)}`
            },
            serviceFeeToFen(){
                if(this.serviceFee){

                    return Number(Math.round(this.serviceFee*100))
                }
            },
            calcDaysType(){
                if(this.payway == 'HBFX') return 'DAY'
                return 'PERIOD'
            },
            saveDays(){
                if(this.isPublish){
                    if(this.payway == 'HBFX'){
                        return this.days
                    }
                    else{
                        return this.periods
                    }
                }
                else{
                    if(this.detail){
                        if(this.detail.repayWay == 'HBFX'){
                            return this.days
                        }
                        else{
                            return this.periods
                        }
                    }
                }
            },
            realDays(){
                if(this.number == 'default'){
                    if(this.payway == 'HBFX'){
                        let now = moment()
                        let diff = moment(new Date(this.days))
                        let diffDays = Math.ceil(diff.diff(now,'days',true))
                        return diffDays || ''
                    }
                    else{
                        return this.periods
                    }
                }
                else{
                    if(this.detail.repayWay == 'HBFX'){
                        return this.days
                    }
                    else{
                        return this.periods
                    }
                }
            },
            canCalc(){
                // publish
                if(this.isPublish){
                    if(!this.amount) return false
                    if(!this.monthSelect) return false
                    if(!this.serviceFee) return false

                    return true
                }

                // apply
                if(!this.amount) return false
                if(!this.realDays) return false

                return true
            },
            noCalc(){
                return _.isEmpty(this.calcObject)
            },
            isPublicBoolean(){
                if(this.isPublic == 0){
                    return false
                }
                return true
            }
        },
        methods:{
            // actions
            ...mapActions([
                'showLoading',
                'hideLoading',
                'setMsgTip',
                'setLoanInApplyForm',
                'setLoanInPublishForm',
                'removeLoanInForm'
            ]),

            //
            setCity(cityInfo){
                this.cityInfo = cityInfo
                // console.log(this.cityInfo)
            },

            // filters
            timestampToDate(timestamp){
                if(!timestamp) return this.placeholder
                return moment(timestamp).format('YYYY-MM-DD')
            },

            // function
            setMax(){
                // console.log(Math.round(this.quota) / 100)
                if(this.amountToFen > 900000){
                    this.amount = 9000
                }
                if (!Number(this.amount)) {
                  this.setMsgTip({
                      text:'请输入正确格式的数字',
                      type:'warn'
                  })
                  this.amount = this.amount.substr(0, this.amount.length - 1)
                }
            },
            caclServiceFeeRate(rate){
                let persent = rate / 100 + '%'
                return persent
            },
            payFinish(password){
                this.password = password
                this.showPayPassword = false
                if(!this.isPublish){
                    this.apply()
                }
                else{
                    this.publish()
                }
            },
            saveForm(){
                if(!this.isPublish){
                    console.log(this.realDays)
                    this.setLoanInApplyForm({
                        amount:this.amount,
                        days:this.saveDays,
                        isAccredit:this.isAccredit,
                        payway:this.detail.repayWay,
                    })
                }
                else{
                    this.setLoanInPublishForm({
                        amount:this.amount,
                        days:this.saveDays,
                        serviceFee:this.serviceFee,
                        payway:this.payway,
                        yearRate:this.yearRate,
                        isPublic:this.isPublic,
                    })
                }
            },
            goRouter(name){
                this.$router.push({
                    name:name
                })
            },
            goUse(){
                this.saveForm()
                this.$router.push({
                    name:'loan-in-want-use'
                })
            },
            goSuccess(no){
                this.removeLoanInForm()
                this.$router.replace({
                    name:'loan-in-success',
                    params:{
                        no:no
                    }
                })
            },
            goPay(){
                this.payStatus = true
                console.log(1)
            },
            goDetail(item){
                this.$router.push({
                    name:'user-detail',
                    params:{
                        id:item.userId,
                    }
                })
            },
            calc(){
                if(!this.canCalc) return
                this.loading_calc = true
                if(!this.isPublish){
                    loanInApi.calc({
                        borrowAmount:this.amountToFen,
                        repayWay:this.detail.repayWay,
                        borrowDays:this.realDays,
                        yearRate:this.detail.yearRate,
                        daysType:this.detail.daysType,
                        serviceFee:this.detail.serviceFee,
                        serviceFeeRate:this.detail.serviceFeeRate,
                    })
                    .then(result=>{
                        this.calcObject = result
                        this.loading_calc = false
                    })
                    .catch(error=>{
                        console.error(error)
                        this.loading_calc = false
                    })
                }
                else{
                    return
                }
            },
            serviceFeeChange(){
                let maxServiceFee = Number((this.amount * 0.12).toFixed(2))
                if(!this.amount){
                    this.setMsgTip({
                        text:'请先输入借款金额',
                        type:'warn'
                    })
                    return
                }
                if(this.amount < 100){
                    this.setMsgTip({
                        text:'借款金额不能小于100元',
                        type:'warn'
                    })
                    return
                }
                if(this.serviceFee && !rules.number(+this.serviceFee)){
                    this.setMsgTip({
                        text:'服务费必须为整数',
                        type:'warn'
                    })
                    this.serviceFee = ''
                    return
                }
                if(+this.serviceFee > maxServiceFee){
                    this.setMsgTip({
                        text:`服务费不能超过${maxServiceFee}元`,
                        type:'warn'
                    })
                    return
                }
                this.calc()

            },
            confirm(){
                if(this.userInfo.isExpired){
                    this.setMsgTip({
                        text:'信用报告已过期，请重新认证',
                        type:'warn',
                    })
                    this.$router.push({
                        name:'user-credit-report-list'
                    })
                    return false
                }
                if(!this.userInfo.creditReport || (this.userInfo.creditReport && this.userInfo.creditReport.status != 'OK' )){
                    this.setMsgTip({
                        text:'请先完善信用报告',
                        type:'warn',
                    })
                    this.$router.push({
                        name:'user-credit-report-list'
                    })
                    return false
                }
                if(!this.isPublish){
                    let params = {
                        amountForm:this.detail.lendAmountFrom,
                        amountTo:this.detail.lendAmountTo,
                        amount:this.amountToFen,
                        days:this.realDays || '',
                        usage:this.usage,
                    }
                    if(!LoanInApplyValidation(params)) return

                    this.show_confirm_borrow = true
                }
                else{
                    let params = {
                        amountForm:this.detail.lendAmountFrom,
                        amountTo:this.detail.lendAmountTo,
                        amount:this.amount,
                        days:this.monthSelect,
                        usage:this.usage,
                        serviceFee:0,
                    }
                    if(!LoanInPublishValidation(params)) return

                    if (this.cityInfo.cityName === '重庆市' || this.cityInfo.cityName === '北京市' || this.cityInfo.cityName === '天津市' || this.cityInfo.cityName === '上海市') {
                      this.cityInfo.cityName = ''
                      this.cityInfo.cityId = ''
                    } else {
                      if (this.cityInfo.provName === '' || this.cityInfo.cityName === '' || this.cityInfo.provId === '' || this.cityInfo.cityId === ''){
                        this.setMsgTip({
                            text:'请选择地区',
                            type:'warn',
                        })
                        return false
                      }
                    }

                    this.show_confirm_borrow = true
                }
            },
            confirmBorrow(){
                /*if(!this.isPay){
                    if(this.isPublish){
                        // this.$router.push({
                        //     name:'user-credit-report-index',
                        //     query:{
                        //         borrowAmount:this.amountToFen,
                        //         borrowDays:this.monthSelect,
                        //         borrowUsage:this.usage,
                        //         ip: this.ip,
                        //         ipProvince: this.cityInfo.provName,
                        //         ipCity: this.cityInfo.cityName,
                        //         provinceId: this.cityInfo.provId,
                        //         cityId: this.cityInfo.cityId,
                        //         type:'pass',
                        //         router:'loan-in-want-index'
                        //     }
                        // })
                        this.apply()
                    }
                    else{
                        this.$router.push({
                            name:'user-credit-report-index',
                            query:{
                                lendNo:this.number,
                                addSay:this.loanInForm.intro,
                                isAccredit:this.isAccredit,
                                borrowAmount:this.amountToFen,
                                borrowDays:this.realDays,
                                borrowUsage:this.usage,
                                type:'pass',
                                router:'loan-in-want-index',
                                mode:'apply'
                            }
                        })
                    }
                    return
                }*/
                // test start
                // this.$router.push({
                //     name:'user-credit-report-index',
                //     query:{
                //         borrowAmount:this.amountToFen,
                //         borrowDays:this.monthSelect,
                //         borrowUsage:this.usage,
                //         ip: this.ip,
                //         ipProvince: this.cityInfo.provName,
                //         ipCity: this.cityInfo.cityName,
                //         provinceId: this.cityInfo.provId,
                //         cityId: this.cityInfo.cityId,
                //         type:'pass',
                //         router:'loan-in-want-index'
                //     }
                // })
                // return
                // test end
                this.show_confirm_borrow = false;
                //this.publish()
                if(!this.isPublish){
                    this.apply()
                }
                else{
                    this.publish()
                }
            },
            apply(){
                this.showLoading()
                let data = {
                    lendNo:this.number,
                    addSay:this.loanInForm.intro,
                    isAccredit:this.isAccredit,
                    borrowAmount:this.amountToFen,
                    borrowDays:this.realDays,//this.monthSelect,,
                    borrowUsage:this.usage,
                   // tradePassword:this.password
                }
                loanInApi.apply(data)
                .then(result=>{
                    this.hideLoading()
                    this.setMsgTip({
                        text:'申请借款成功！',
                        type:'success'
                    })
                    this.setLoanInApplyForm({},'remove')
                    this.$router.push({
                        name:'loan-in-index'
                    })
                })
                .catch(error=>{
                    console.error(error)
                    this.hideLoading()
                })
            },
            publish(){
                this.showLoading()


                // let ipCity = (this.cityInfo.cityName === '重庆市' ||
                //               this.cityInfo.cityName === '北京市' ||
                //               this.cityInfo.cityName === '天津市' ||
                //               this.cityInfo.cityName === '上海市') ? '' : this.cityInfo.cityName
                //
                // let cityId = (this.cityInfo.cityName === '重庆市' ||
                //               this.cityInfo.cityName === '北京市' ||
                //               this.cityInfo.cityName === '天津市' ||
                //               this.cityInfo.cityName === '上海市') ? '' : this.cityInfo.cityId

                // console.log(ipCity, cityId, this.cityInfo)

                let data = {
                    daysType:this.calcDaysType,
                    borrowAmount:this.amountToFen,
                    repayWay:this.payway,
                    borrowDays:this.monthSelect,
                    yearRate:2400,
                    serviceFee:0,
                    borrowUsage:this.usage,
                    isPublic:this.isPublicBoolean,
                    addSay:this.loanInForm.intro,
                    tradePassword:this.password,
                    ip: this.ip,
                    ipProvince: this.cityInfo.provName,
                    ipCity: this.cityInfo.cityName,
                    provinceId: this.cityInfo.provId,
                    cityId: this.cityInfo.cityId
                }

                loanInApi.publish(data)
                .then(result=>{
                    this.hideLoading()
                    this.setLoanInPublishForm({},'remove')
                    // localStorage.setItem('cityName', this.cityInfo.cityName)
                    this.goSuccess(result.borrowNo)
                })
                .catch(error=>{
                    console.error(error)
                    this.hideLoading()
                })
            },
            getQuota(){
                return userApi.quota()
                .then(result=>{
                    this.quota = result.usableQuota
                })
            },
            getDetail(){
                return loanOutApi.detailOther({
                    lendNo:this.number
                })
                .then(result=>{
                    let type = result.daysType
                    let from = result.lendDaysFrom
                    let to = result.lendDaysTo
                    let array = []
                    if(type == 'DAY'){
                        _.each(daysList,(value,index)=>{
                            if(value.value>=from && value.value<=to ){
                                array.push(value)
                            }
                        })
                        this.daysList = array
                    }
                    else{
                        _.each(periodsList,(value,index)=>{
                            if(+(value.value)>=from && +(value.value)<=to ){
                                array.push(value)
                            }
                        })
                        this.periodsList = array
                    }



                    this.detail = result
                })
            },
            getUsage(num){
                this.showLoading()
                loanInApi.usage()
                .then(result=>{
                    this.hideLoading()
                    let arr = []
                    _.each(result,(value,index)=>{
                        arr.push({
                            value:value.name,
                            display:value.name
                        })
                    })
                    this.usageList = arr
                })
                .catch(error => {
                    console.error(error)
                    this.hideLoading()
                })
            },
            getZoneService(num){
                this.showLoading()
                loanInApi.zoneService()
                .then(result=>{
                    this.hideLoading()
                    let arr = []
                    _.each(result.zoneList,(value,index)=>{
                        let arrChildren = []
                        // 判断是否为四个直辖市
                        if (value.children.length === 1) {
                          arrChildren.push({
                            "city_id": value.id,
                            "prov_name": value.name,
                            "city_name": value.name,
                            "prov_id": value.id
                          })
                        } else {
                          _.each(value.children, (item, index) => {
                              arrChildren.push({
                                "city_id": item.id,
                                "prov_name": value.name,
                                "city_name": item.name,
                                "prov_id": value.id
                              })
                            })
                        }
                        arr.push({
                            name:value.name,
                            info: arrChildren
                        })
                        // 获取默认省市的ID
                        if (this.cityInfo !== '' && this.cityInfo.provName === value.name) {
                          this.cityInfo.provId = value.id
                          if (value.children.length !== 0) {
                            _.each(value.children, (item, index) => {
                              if (this.cityInfo.cityName === item.name) {
                                this.cityInfo.cityId = item.id
                              }
                              })
                          } else {
                            this.cityInfo.cityId = ''
                          }
                        }
                    })
                    this.addressList = arr
                    this.ip = result.ip
                })
                .catch(error => {
                    console.error(error)
                    this.hideLoading()
                })
            },
        },
        created(){
            console.log(remote_ip_info)
            // this.cityInfo = {
            //     cityName: returnCitySN.cname.split('省').length > 1 ? returnCitySN.cname.split('省')[1] : '',
            //     provName: returnCitySN.cname.split('省').length > 1 ? returnCitySN.cname.split('省')[0] + '省' : returnCitySN.cname.split('省')[0]
            // }

            this.cityInfo = {
                cityName: remote_ip_info.city ? remote_ip_info.city: '',
                provName: remote_ip_info.province ? remote_ip_info.province: '',
            }

            if(this.isPublish){
                if(this.$route.query.borrowAmount){
                    this.showLoading()
                    let data = {
                        daysType:"DAY",
                        repayWay:'HBFX',
                        yearRate:2400,
                        serviceFee:0,
                        isPublic:true,
                        borrowAmount:this.$route.query.borrowAmount,
                        borrowDays:this.$route.query.borrowDays,
                        borrowUsage:this.$route.query.borrowUsage,
                        ip: this.$route.query.ip,
                        ipProvince: this.$route.query.ipProvince,
                        ipCity: this.$route.query.ipCity,
                        provinceId: this.$route.query.provinceId,
                        cityId: this.$route.query.cityId,
                    }
                    // console.log(data)
                    // return
                    loanInApi.publish(data)
                    .then(result=>{
                        this.hideLoading()
                        // localStorage.setItem('cityName', this.cityInfo.cityName)
                        this.goSuccess(result.borrowNo)
                    })
                    .catch(error=>{
                        console.error(error)
                        this.hideLoading()
                    })
                    return
                }
            }
            else{
                if(this.$route.query.borrowAmount){
                    this.showLoading()
                    let data = {
                        lendNo:this.$route.params.number,
                        borrowAmount:this.$route.query.borrowAmount,
                        borrowDays:this.$route.query.borrowDays,
                        borrowUsage:this.$route.query.borrowUsage,
                    }
                    loanInApi.apply(data)
                    .then(result=>{
                        this.hideLoading()
                        this.setMsgTip({
                            text:'申请借款成功！',
                            type:'success'
                        })
                        this.$router.push({
                            name:'loan-in-index'
                        })
                    })
                    .catch(error=>{
                        console.error(error)
                        this.hideLoading()
                    })
                    return
                }
            }
            this.pageLoaded = true
            this.showLoading()
            this.amount = this.loanInForm.amount || ''
            this.isAccredit = this.loanInForm.isAccredit || 1
            this.serviceFee = this.loanInForm.serviceFee || ''
            this.yearRate = this.loanInForm.yearRate || ''
            this.isPublic = this.loanInForm.isPublic || ''

            this.getUsage()
            this.getZoneService()


            if(this.isPublish){
                document.title = '我要借款'
                this.buttonText = '确定发布'
                setTimeout(()=>{
                    this.showTips = true
                },300)
                this.calc()
            }
            else{
                document.title = '申请借款'
                this.buttonText = '马上申请'
                this.getDetail()
                .then(result=> {
                    this.hideLoading()
                    setTimeout(()=>{
                        this.showTips = true
                    },300)
                    this.calc()
                })
                .catch(error=> {
                    console.log(error);
                    this.hideLoading()
                    setTimeout(()=>{
                        this.showTips = true
                    },300)
                    this.calc()
                });
            }
        }
    }
</script>

<style lang="scss">
    @import "../sass/variables";
    @import "../sass/extends";
    @import "../sass/mixins";
    .loan-in-want-index{
        //  .component-modal__container{
        //          height: 85%!important;
        // }
        transform:translate3d(0,0,0);
        .wrapper{
            padding-bottom: 100px;
        }
        .amountRate{

        }
        .explain{
            @extend %font-caption;
            padding:8px 24px 0 24px;
            color:$importColor;
        }
        .money-info{
            margin-top:16px;
            position: relative;
        }
        .money-info__header{
            display: flex;
        }
        .money-info__title{
            @extend %font-body1;
            color:$importColor;
            padding-bottom: 8px;
            margin-bottom: 8px;
            border-bottom:1px solid $sectionColor;
        }
        .money-info__box{
            width: 100%;
            flex:1;
            position: relative;
            &:nth-of-type(2n){
                margin-left:24px;
            }
        }
        .money-info__item{
            @extend %font-caption;
            padding-top: 4px;
            display: flex;
            justify-content:space-between;
            &.fade{
                opacity:0;
            }
            &.today{
                color:$grayLight;
            }
        }
        .money-info__number{
            @extend %font-subhead;
            color:$orange;
            padding-top: 4px;
            text-align:right
        }
        .plan{
            padding-top: 16px;
        }
        .agreement{
            padding:16px;
        }
        .agreement__text{
            @extend %font-body1;
            font-weight:normal;
            display: block;
            color:$importColor;
        }
        .tips{
            @extend %font-caption;
            color:rgba(#000,.26);
            padding:0 16px 0 16px;
            line-height: 20px;
        }
        .have-two-item{
            p{
                @extend %font-subhead;
                padding-left: 8px;
            }
        }
        .year-rate{
            padding-left: 7px!important;
        }
        .real-days{
            @extend %font-subhead;
            position: absolute;
            right:48px;
        }
        .repay-time{
            .form__value{
                z-index:2;
                &.choose{
                    .component-picker-date__input{
                        padding-right: 74px;
                    }
                }
            }
        }
    }

</style>
